package com.aleaho.cftrack.activity;


import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.R;
import com.aleaho.cftrack.entity.MenuEntity;
import com.aleaho.cftrack.font.NewIcon;
import com.aleaho.cftrack.adapter.MenuAdapter;
import com.aleaho.cftrack.http.entity.LoginEntity;
import com.aleaho.cftrack.listener.ItemOnClickListener;
import com.aleaho.cftrack.presenter.MainPresenter;
import com.aleaho.cftrack.receiver.TrackReceiver;
import com.aleaho.cftrack.utils.BitmapUtil;
import com.aleaho.cftrack.utils.Constants;
import com.aleaho.cftrack.utils.TrackConsts;
import com.aleaho.cftrack.utils.ViewUtil;
import com.aleaho.cftrack.view.MainView;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.baidu.trace.model.StatusCodes;
import com.beardedhen.androidbootstrap.BootstrapCircleThumbnail;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements ItemOnClickListener,
        View.OnClickListener, MainView {

    private RecyclerView indexRecyclerView;
    private VirtualLayoutManager layoutManager;
    private List<MenuEntity> menuData;

    private CFTrackApplication trackApp = null;
    private ViewUtil mViewUtil = null;

    private LoginEntity le = null;


    @BindView(R.id.tv_username)
    TextView tvUserName;
    @BindView(R.id.tv_userinfo)
    TextView tvUserInfo;
    @BindView(R.id.bct_avatar)
    BootstrapCircleThumbnail civAvatar;


    private NotificationManager mNotificationManager = null;
    private PowerManager mPowerManager = null;
    private PowerManager.WakeLock mWakeLock = null;
    private TrackReceiver mTrackReceiver = null;

    /**
     * 鹰眼位置信息打包周期
     */
    private int packInterval = TrackConsts.DEFAULT_PACK_INTERVAL;

    /**
     * 鹰眼位置信息采集周期
     */
    private int gratherInterval = TrackConsts.DEFAULT_GATHER_INTERVAL;


    private MainPresenter mMainPresenter = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        trackApp = (CFTrackApplication) getApplicationContext();

        mMainPresenter = new MainPresenter(trackApp, this);

        mPowerManager = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mViewUtil = new ViewUtil();
        BitmapUtil.init();
        initData();
        initView();

        // 开启鹰眼服务

        startTrace();
    }

    /**
     * 初始化主界面个人信息
     */
    private void initView() {

        initRecyclerView();

        le = trackApp.getLoginEntity();

        if (le == null) {
            return;
        }

        tvUserInfo.setText(le.getLoginUser().getPermission().getDutyname() + "|"
                + le.getLoginUser().getDepartment().getDepartmentname());

        tvUserName.setText(le.getLoginUser().getName());

        String avatarUrl = Constants.BASE_URL + le.getLoginUser().getAvatar().getImage().replaceFirst("/", "");

        Log.i(Constants.TAG, avatarUrl);
        Picasso.with(this).load(avatarUrl)
                .resize(100, 100)
                .centerCrop()
                .into(civAvatar);
    }


    /**
     * 初始化主界面的九宫格菜单数据
     */
    private void initData() {

        menuData = new ArrayList<>();
        menuData.add(new MenuEntity(getString(R.string.activity_location), NewIcon.ICON_WEIZHI, LocationActivity.class));
        menuData.add(new MenuEntity(getString(R.string.activity_track), NewIcon.ICON_GUIJI, TrackQueryActivity.class));
        menuData.add(new MenuEntity(getString(R.string.activity_sign), NewIcon.ICON_QIANDAO, SignActivity.class));
        menuData.add(new MenuEntity("外出报备", NewIcon.ICON_WAICHU, TrackQueryActivity.class));
        menuData.add(new MenuEntity("工作日志", NewIcon.ICON_RIZHI, LocationActivity.class));
        menuData.add(new MenuEntity("走访商户", NewIcon.ICON_SHANGHU, TrackQueryActivity.class));
        menuData.add(new MenuEntity("商户列别", NewIcon.ICON_LIEBIAO, LocationActivity.class));
    }

    /**
     * 初始化主界面九宫格菜单界面
     * 使用阿里巴巴的开源项目VLayout进行布局。
     */
    private void initRecyclerView() {

        //找到RecyclerView
        indexRecyclerView = (RecyclerView) findViewById(R.id.rcMainView);
        //初始化Vlayout的布局管理器
        layoutManager = new VirtualLayoutManager(this);

        //将Vlayout布局管理器与RecyclerView进行关联。
        indexRecyclerView.setLayoutManager(layoutManager);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        indexRecyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 10);


        final DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, true);

        indexRecyclerView.setAdapter(delegateAdapter);

        final List<DelegateAdapter.Adapter> adapters = new LinkedList<>();

        GridLayoutHelper menuLayoutHelper = new GridLayoutHelper(3);
        menuLayoutHelper.setAutoExpand(false);
        menuLayoutHelper.setWeights(new float[]{33, 33, 33});
        menuLayoutHelper.setAspectRatio(3);
        menuLayoutHelper.setItemCount(menuData.size());
        MenuAdapter menuAdapter = new MenuAdapter(this, menuLayoutHelper, menuData,
                new VirtualLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300));

        menuAdapter.setItemOnClickListener(this);

        adapters.add(menuAdapter);

        delegateAdapter.setAdapters(adapters);
    }

    @Override
    public int getResourcesId() {
        return R.layout.activity_main;
    }


    /**
     * 主界面的按钮事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            /**
             * 用户信息界面的退出按钮。
             */
            case R.id.right_view:
                confirmDialog(R.string.logout, "你确定要退出程序吗？",
                        R.string.dialog_ok, R.string.dialog_ok);
                break;
            default:
                break;
        }
    }

    /**
     * 菜单界面九宫格中菜单的点击事件。
     *
     * @param view
     * @param postion
     */
    @Override
    public void onItemClick(View view, int postion) {
        System.out.println("点击了第" + postion + "行");
        Log.i("VLayout", "点击了第" + postion + "行");

        Toast.makeText(this, menuData.get(postion).name, Toast.LENGTH_SHORT).show();

        Intent i = new Intent(this, menuData.get(postion).toActivity);
        startActivity(i);
    }


    /**
     * 对话框，在客户点击退出时弹出，让客户进行再确认。
     * 当客户确定退出程序，删除最后登陆的客户信息，使用finish方法注销MainActivity。
     * 界面跳转到Login界面。
     *
     * @param titleRes 对话框标题
     * @param content  对话框内容
     * @param posRes   对话框确认按钮的文字
     * @param resTip
     */
    private void confirmDialog(int titleRes, String content, int posRes, final int resTip) {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(titleRes)
                .titleColor(Color.parseColor("#2196F3"))
                .content(content)
                .positiveText(posRes)
                .onPositive(new MaterialDialog.SingleButtonCallback() {

                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        //退出
                        trackApp.logout();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);

                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                        mMainPresenter.stopGather();
                        mMainPresenter.stopTrace();

                        startActivity(intent);
                        finish();
                    }
                })

                .negativeText(R.string.dialog_cancel)
                .onNegative(new MaterialDialog.SingleButtonCallback() {

                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                    }
                })
                .show();
    }


    @Override
    public void setTraceStyle() {

    }

    @Override
    public void showMessage(String message) {
        mViewUtil.showToast(this, message);
    }


    /**
     * 注册广播（电源锁，GPS状态）
     */
    @Override
    public void registerReceiver() {

        if (trackApp.isRegisterReceiver) {
            return;
        }

        if (null == mWakeLock) {
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");

        }

        if (null == mTrackReceiver) {
            mTrackReceiver = new TrackReceiver(mWakeLock);
        }


        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(StatusCodes.GPS_STATUS_ACTION);
        trackApp.registerReceiver(mTrackReceiver, filter);
        trackApp.isRegisterReceiver = true;
    }

    /**
     *
     */
    @Override
    public void unregisterPowerReceiver() {
        if (!trackApp.isRegisterReceiver) {
            return;
        }
        if (null != mTrackReceiver) {
            trackApp.unregisterReceiver(mTrackReceiver);
        }
        trackApp.isRegisterReceiver = false;

    }

    @Override
    public void notify(int id, Notification notification) {
        mNotificationManager.notify(id, notification);
    }

    /**
     * 按下返回键停止监听。
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();

        mMainPresenter.stopGather();
        mMainPresenter.stopTrace();
    }


    public void startTrace() {
        mMainPresenter.startTrace();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapUtil.clear();
    }
}
